package org.example.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import jakarta.annotation.Resource;
import org.example.order.bean.Order;
import org.example.order.feign.ProductFeignClient;
import org.example.order.service.OrderService;
import org.example.product.bean.Product;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author : wer
 * @Date: 2025/6/21 16:12
 * @Description: 订单服务接口实现
 */

@Service
public class OrderServiceImpl implements OrderService {


    @Resource
    RestTemplate restTemplate;

    @Resource
    ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
        // Product product = createProduct(productId);

        // 改用feign进行远程调用（自动负载均衡）
        Product product = productFeignClient.getProductById(productId);

        Order order = new Order();
        order.setId(1L);
        BigDecimal multiply = product.getPrice().multiply(new BigDecimal(product.getNum()));
        order.setTotalAmount(multiply);
        order.setUserId(userId);
        order.setAddress("America");
        order.setNickName("Vespucci");
        order.setProductList(List.of(product));
        return order;
    }

    // 兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setUserId(userId);
        order.setAddress("异常信息：" + e.getClass().getSimpleName());
        order.setNickName("未知用户");
        order.setTotalAmount(new BigDecimal(0));
        return order;
    }

    private Product createProduct(Long productId) {
        // 使用负载均衡，直接传入服务名称service-product发送请求
        String url = "http://service-product/product/" + productId;
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
